﻿<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>教务管理系统 - 成绩管理</title>
    <link href="${pageContext.request.contextPath}/resources/bootstrap5/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons - 本地版本 -->
    <link href="${pageContext.request.contextPath}/resources/bootstrap-icons/1.11.3/bootstrap-icons.css" rel="stylesheet">
    <!-- Bootstrap Icons - 备用CDN -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <!-- 第二个备用CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .header {
            background-color: #1976d2;
            color: white;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: fixed;
            width: 100%;
            top: 0;
            z-index: 1000;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .header h2 {
            margin: 0;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
        }

        .header h2 img {
            height: 36px;
            margin-right: 10px;
        }

        .header .breadcrumb {
            margin: 0;
            background: transparent;
            color: white;
        }

        .header .breadcrumb a {
            color: rgba(255,255,255,0.8);
            text-decoration: none;
        }

        .header .breadcrumb a:hover {
            color: white;
        }

        .header .breadcrumb-item.active {
            color: white;
        }

        .header .breadcrumb-item+.breadcrumb-item::before {
            color: rgba(255,255,255,0.6);
        }

        /* 侧边栏样式 */
        .sidebar {
            position: fixed;
            top: 56px;
            left: 0;
            bottom: 0;
            width: 250px;
            background-color: white;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            overflow-y: auto;
            z-index: 100;
            padding-top: 20px;
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-menu > li {
            margin-bottom: 5px;
        }

        .sidebar-menu > li > a {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            color: #333;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }

        .sidebar-menu > li > a:hover {
            background-color: #f0f0f0;
            border-left-color: #1976d2;
        }

        .sidebar-menu > li > a.active {
            background-color: #e3f2fd;
            border-left-color: #1976d2;
            color: #1976d2;
        }

        .sidebar-menu > li > a i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }

        .sidebar-submenu {
            list-style: none;
            padding-left: 53px;
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }

        .sidebar-menu > li.open .sidebar-submenu {
            max-height: 500px;
        }

        .sidebar-submenu > li > a {
            display: block;
            padding: 8px 0;
            color: #666;
            text-decoration: none;
            transition: all 0.3s;
        }

        .sidebar-submenu > li > a:hover {
            color: #1976d2;
        }

        .sidebar-submenu > li > a.active {
            color: #1976d2;
            font-weight: 500;
        }

        /* 内容区样式 */
        .content {
            margin-left: 250px;
            padding: 76px 20px 20px;
        }

        /* 用户名下拉菜单样式 */
        .header-user {
            display: flex;
            align-items: center;
            position: relative;
        }
        .header-user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 8px;
            object-fit: cover;
            background: #fff;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .header-user-avatar:hover {
            transform: scale(1.1);
        }
        .header-user-name {
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        .user-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            min-width: 160px;
            z-index: 1001;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s ease;
            margin-top: 8px;
        }
        .user-dropdown.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }
        .user-dropdown::before {
            content: '';
            position: absolute;
            top: -6px;
            right: 20px;
            width: 12px;
            height: 12px;
            background: #fff;
            transform: rotate(45deg);
            box-shadow: -2px -2px 4px rgba(0,0,0,0.1);
        }
        .user-dropdown-item {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            color: #333;
            text-decoration: none;
            transition: background 0.2s;
            border-bottom: 1px solid #f0f0f0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        .user-dropdown-item:last-child {
            border-bottom: none;
        }
        .user-dropdown-item:hover {
            background: #f8f9fa;
            color: #1976d2;
        }
        .user-dropdown-item i {
            margin-right: 8px;
            width: 16px;
            text-align: center;
        }

        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .card-header {
            padding: 15px 20px;
            background-color: white;
            border-bottom: 1px solid #eee;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-body {
            padding: 20px;
        }

        .search-bar {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 18px;
            flex-wrap: nowrap;
        }

        .search-bar input, .search-bar select {
            border-radius: 8px;
            border: 1px solid #e3e3e3;
            padding: 6px 14px;
            font-size: 1rem;
            flex: 1;
            min-width: 150px;
        }

        .search-bar .btn {
            border-radius: 8px;
            font-size: 1rem;
            padding: 6px 18px;
            font-weight: 500;
            box-shadow: none;
            flex-shrink: 0;
        }

        .btn-primary {
            background: #1976d2;
            border: none;
        }

        .btn-primary:hover {
            background: #1565c0;
        }

        .btn-warning {
            background: #ffb300;
            color: #fff;
            border: none;
        }

        .btn-warning:hover {
            background: #ff9800;
            color: #fff;
        }

        .btn-success {
            background: #4caf50;
            border: none;
        }

        .btn-success:hover {
            background: #388e3c;
        }

        .btn-danger {
            background: #f44336;
            border: none;
        }

        .btn-danger:hover {
            background: #d32f2f;
        }

        .table {
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .table thead th {
            background: #f8f9fa;
            color: #1976d2;
            font-weight: bold;
            text-align: center;
            border-bottom: 2px solid #e3e3e3;
        }

        .table tbody tr {
            transition: background 0.2s;
        }

        .table tbody tr:hover {
            background: #f1f8ff;
        }

        .table td, .table th {
            vertical-align: middle !important;
            text-align: center;
        }

        .pagination {
            justify-content: center;
            margin-top: 12px;
        }

        .pagination .page-item .page-link {
            border-radius: 6px !important;
            margin: 0 2px;
            color: #1976d2;
            border: none;
            background: #fff;
            font-weight: 500;
            transition: background 0.2s, color 0.2s;
        }

        .pagination .page-item.active .page-link {
            background: #1976d2;
            color: #fff;
        }

        .pagination .page-item .page-link:hover {
            background: #e3f2fd;
            color: #1565c0;
        }

        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s;
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .content {
                margin-left: 0;
            }

            .search-bar {
                flex-wrap: wrap;
            }

            .search-bar input, .search-bar select {
                min-width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
<!-- 头部导航栏 -->
<div class="header">
    <div class="header-left">
        <h2><img src="${pageContext.request.contextPath}/resources/images/logo.png" alt="Logo"> 教务管理系统</h2>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="${pageContext.request.contextPath}/teacher/home">教师首页</a></li>
                <li class="breadcrumb-item active">成绩管理</li>
            </ol>
        </nav>
    </div>

    <!-- 用户名下拉菜单 -->
    <div class="header-user" id="userDropdownContainer">
        <img src="${pageContext.request.contextPath}/resources/images/baimao.png" class="header-user-avatar" alt="用户名头像" id="userAvatar">
        <span class="header-user-name" id="userName">
                <c:choose>
                    <c:when test="${not empty currentTeacher and not empty currentTeacher.user and not empty currentTeacher.user.realName}">
                        ${currentTeacher.user.realName}
                    </c:when>
                    <c:when test="${not empty sessionScope.loggedInUser and not empty sessionScope.loggedInUser.realName}">
                        ${sessionScope.loggedInUser.realName}
                    </c:when>
                    <c:when test="${not empty sessionScope.loggedInUser and not empty sessionScope.loggedInUser.username}">
                        ${sessionScope.loggedInUser.username}
                    </c:when>
                    <c:otherwise>
                        教师
                    </c:otherwise>
                </c:choose>
            </span>
        <div class="user-dropdown" id="userDropdown">
            <a href="#" class="user-dropdown-item" onclick="showProfileModal()">
                <i class="bi bi-person-circle"></i>
                个人信息
            </a>
            <a href="${pageContext.request.contextPath}/teacher/changePassword" class="user-dropdown-item">
                <i class="bi bi-key"></i>
                修改密码
            </a>
            <a href="${pageContext.request.contextPath}/user/logout" class="user-dropdown-item">
                <i class="bi bi-box-arrow-right"></i>
                退出系统
            </a>
        </div>
    </div>
</div>

<!-- 侧边栏 -->
<div class="sidebar">
    <ul class="sidebar-menu">
        <li>
            <a href="${pageContext.request.contextPath}/teacher/home">
                <i class="bi bi-house-door"></i> 教师首页
            </a>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-megaphone"></i> 信息公告
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/teacher/notifications/academic">教学事务通知</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/notifications/exam">考试安排</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/notifications/classroom">教室安排</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-book"></i> 教学管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/teacher/courses">我的课程</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/course-students">选课学生</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/homework">作业管理</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/grades" class="active">成绩管理</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/attendance">考勤管理</a></li>
            </ul>
        </li>
        <li class="open">
            <a href="#" class="has-submenu">
                <i class="bi bi-person-check"></i> 学生管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/teacher/evaluation">教学评价</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/leave">请假审批</a></li>
            </ul>
        </li>
        <li>
            <a href="${pageContext.request.contextPath}/user/logout">
                <i class="bi bi-box-arrow-right"></i> 退出系统
            </a>
        </li>
    </ul>
</div>

<!-- 主要内容区 -->
<div class="content">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">成绩管理</h1>
    </div>

    <c:if test="${not empty error}">
        <div class="alert alert-danger" role="alert">
                ${error}
        </div>
    </c:if>

    <div class="card">
        <div class="card-body">
            <!-- 课程选择 -->
            <div class="d-flex justify-content-between align-items-center mb-3">
                <form class="search-bar" method="get" action="${pageContext.request.contextPath}/teacher/grades" style="margin-bottom: 0;">
                    <select class="form-select" name="courseId" id="courseSelect" style="min-width: 200px;" onchange="this.form.submit()">
                        <option value="">所有课程</option>
                        <c:forEach var="course" items="${teacherCourses}">
                            <option value="${course.id}" ${searchCourseId == course.id ? 'selected' : ''}>
                                <c:out value="${course.name}"/>
                            </option>
                        </c:forEach>
                    </select>
                    <input type="text" class="form-control" name="studentSearch" value="${studentSearch}" placeholder="请输入学生姓名" style="min-width: 200px;">
                    <button type="submit" class="btn btn-primary">查询</button>
                    <a href="${pageContext.request.contextPath}/teacher/grades" class="btn btn-warning">重置</a>
                </form>

                <button type="button" class="btn btn-success" onclick="showAddGradeModal()">
                    <i class="bi bi-plus-circle"></i> 添加成绩
                    </button>
            </div>

            <!-- 成绩数据表格 -->
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                            <tr>
                                <th style="width: 8%;">编号</th>
                                <th style="width: 15%;">学生姓名</th>
                                <th style="width: 12%;">学号</th>
                                <th style="width: 10%;">班级</th>
                        <th style="width: 12%;">课程名称</th>
                        <th style="width: 10%;">平时成绩</th>
                        <th style="width: 10%;">考试成绩</th>
                        <th style="width: 8%;">总成绩</th>
                                <th style="width: 15%;">操作</th>
                            </tr>
                            </thead>
                    <tbody>
                    <c:choose>
                        <c:when test="${empty grades}">
                            <tr>
                                <td colspan="9" class="text-center text-muted py-4">
                                    <i class="bi bi-inbox" style="font-size: 2rem;"></i>
                                    <br>暂无成绩记录
                                </td>
                            </tr>
                        </c:when>
                        <c:otherwise>
                            <c:forEach var="grade" items="${grades}" varStatus="status">
                                <tr>
                                    <td>${(currentPage - 1) * pageSize + status.index + 1}</td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${not empty grade.student and not empty grade.student.user and not empty grade.student.user.realName}">
                                                ${grade.student.user.realName}
                                            </c:when>
                                            <c:otherwise>未知</c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${not empty grade.student and not empty grade.student.studentNo}">
                                                ${grade.student.studentNo}
                                            </c:when>
                                            <c:otherwise>未知</c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${not empty grade.student and not empty grade.student.clazz and not empty grade.student.clazz.name}">
                                                ${grade.student.clazz.name}
                                            </c:when>
                                            <c:otherwise>未知</c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${not empty grade.course and not empty grade.course.name}">
                                                ${grade.course.name}
                                            </c:when>
                                            <c:otherwise>未知</c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${not empty grade.regularScore}">
                                                <fmt:formatNumber value="${grade.regularScore}" maxFractionDigits="1"/>
                                            </c:when>
                                            <c:otherwise>--</c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${not empty grade.examScore}">
                                                <fmt:formatNumber value="${grade.examScore}" maxFractionDigits="1"/>
                                            </c:when>
                                            <c:otherwise>--</c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${not empty grade.totalScore}">
                                                <span class="badge ${grade.totalScore >= 90 ? 'bg-success' : grade.totalScore >= 80 ? 'bg-primary' : grade.totalScore >= 70 ? 'bg-info' : grade.totalScore >= 60 ? 'bg-warning' : 'bg-danger'}">
                                                    <fmt:formatNumber value="${grade.totalScore}" maxFractionDigits="1"/>
                                                </span>
                                            </c:when>
                                            <c:otherwise>--</c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-primary btn-sm" onclick="editGrade(${grade.id})">
                                            <i class="bi bi-pencil"></i> 编辑
                                        </button>
                                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteGrade(${grade.id})">
                                            <i class="bi bi-trash"></i> 删除
                                        </button>
                                    </td>
                                </tr>
                            </c:forEach>
                        </c:otherwise>
                    </c:choose>
                            </tbody>
                        </table>
                    </div>
            
            <!-- 分页导航 -->
            <c:if test="${totalPages > 1}">
                <nav aria-label="成绩分页">
                    <ul class="pagination justify-content-center">
                        <!-- 上一页 -->
                        <li class="page-item ${currentPage == 1 ? 'disabled' : ''}">
                            <a class="page-link" href="${pageContext.request.contextPath}/teacher/grades?page=${currentPage - 1}&courseId=${searchCourseId}&studentSearch=${studentSearch}">
                                上一页
                            </a>
                        </li>
                        
                        <!-- 页码 -->
                        <c:forEach begin="1" end="${totalPages}" var="i">
                            <li class="page-item ${i == currentPage ? 'active' : ''}">
                                <a class="page-link" href="${pageContext.request.contextPath}/teacher/grades?page=${i}&courseId=${searchCourseId}&studentSearch=${studentSearch}">
                                    ${i}
                                </a>
                            </li>
                        </c:forEach>
                        
                        <!-- 下一页 -->
                        <li class="page-item ${currentPage == totalPages ? 'disabled' : ''}">
                            <a class="page-link" href="${pageContext.request.contextPath}/teacher/grades?page=${currentPage + 1}&courseId=${searchCourseId}&studentSearch=${studentSearch}">
                                下一页
                            </a>
                        </li>
                    </ul>
                </nav>
            </c:if>
        </div>
    </div>
</div>

<!-- 添加成绩模态框 -->
<div class="modal fade" id="addGradeModal" tabindex="-1" aria-labelledby="addGradeModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addGradeModalLabel">
                    <i class="bi bi-plus-circle me-2"></i>添加成绩
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
                <form id="addGradeForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="addCourseSelect" class="form-label">选择课程 <span class="text-danger">*</span></label>
                                <select class="form-select" id="addCourseSelect" name="courseId" required>
                                    <option value="">请选择课程</option>
                                    <c:forEach var="course" items="${teacherCourses}">
                                        <option value="${course.id}">
                                            <c:out value="${course.name}"/>
                                        </option>
                                    </c:forEach>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="addStudentSelect" class="form-label">选择学生 <span class="text-danger">*</span></label>
                                <select class="form-select" id="addStudentSelect" name="studentId" required disabled>
                                    <option value="">请先选择课程</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="regularScore" class="form-label">平时成绩</label>
                                <input type="number" class="form-control" id="regularScore" name="regularScore" 
                                       min="0" max="100" step="0.1" placeholder="请输入平时成绩">
                                <div class="form-text">取值范围：0-100分</div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="examScore" class="form-label">考试成绩</label>
                                <input type="number" class="form-control" id="examScore" name="examScore" 
                                       min="0" max="100" step="0.1" placeholder="请输入考试成绩">
                                <div class="form-text">取值范围：0-100分</div>
                            </div>
                        </div>
                    </div>
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle me-2"></i>
                        <strong>说明：</strong>至少输入平时成绩或考试成绩中的一项。总成绩将自动计算（平时成绩30% + 考试成绩70%）
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-x-circle me-1"></i>取消
                </button>
                <button type="button" class="btn btn-primary" onclick="submitAddGrade()">
                    <i class="bi bi-check-circle me-1"></i>添加成绩
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑成绩模态框 -->
<div class="modal fade" id="editGradeModal" tabindex="-1" aria-labelledby="editGradeModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editGradeModalLabel">
                    <i class="bi bi-pencil me-2"></i>编辑成绩
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
                <form id="editGradeForm">
                    <input type="hidden" id="editGradeId" name="gradeId">
                    <div class="mb-3">
                        <label class="form-label">学生信息</label>
                        <div class="card">
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-sm-4"><strong>学生姓名：</strong></div>
                                    <div class="col-sm-8" id="editStudentName">-</div>
                                </div>
                                <div class="row">
                                    <div class="col-sm-4"><strong>课程名称：</strong></div>
                                    <div class="col-sm-8" id="editCourseName">-</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editRegularScore" class="form-label">平时成绩</label>
                                <input type="number" class="form-control" id="editRegularScore" name="regularScore" 
                                       min="0" max="100" step="0.1" placeholder="请输入平时成绩">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="editExamScore" class="form-label">考试成绩</label>
                                <input type="number" class="form-control" id="editExamScore" name="examScore" 
                                       min="0" max="100" step="0.1" placeholder="请输入考试成绩">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-x-circle me-1"></i>取消
                </button>
                <button type="button" class="btn btn-primary" onclick="submitEditGrade()">
                    <i class="bi bi-check-circle me-1"></i>保存修改
                </button>
            </div>
        </div>
    </div>
</div>

<script src="${pageContext.request.contextPath}/resources/bootstrap5/js/bootstrap.bundle.min.js"></script>
<script>
    // 页面加载完成后执行脚本
    document.addEventListener('DOMContentLoaded', function() {
        console.log('=== 成绩管理页面加载完成 ===');

        // 用户名下拉菜单交互
        const userDropdownContainer = document.getElementById('userDropdownContainer');
        const userDropdown = document.getElementById('userDropdown');

        if (userDropdownContainer && userDropdown) {
            userDropdownContainer.addEventListener('click', function(e) {
                e.stopPropagation();
                userDropdown.classList.toggle('show');
            });

            document.addEventListener('click', function() {
                userDropdown.classList.remove('show');
            });
        }

        // 侧边栏子菜单
        document.querySelectorAll('.has-submenu').forEach(function(item) {
            item.addEventListener('click', function(e) {
                e.preventDefault();
                this.parentNode.classList.toggle('open');
            });
        });

        // 添加课程选择变化事件监听
        document.getElementById('addCourseSelect').addEventListener('change', function() {
            loadCourseStudents(this.value);
        });
    });

    // 显示个人信息模态框
    function showProfileModal() {
        // 关闭用户名下拉菜单
        const dropdown = document.getElementById('userDropdown');
        dropdown.classList.remove('show');
        alert('个人信息功能暂未开放');
    }

    // 显示添加成绩模态框
    function showAddGradeModal() {
        // 重置表单
        document.getElementById('addGradeForm').reset();
        document.getElementById('addStudentSelect').disabled = true;
        document.getElementById('addStudentSelect').innerHTML = '<option value="">请先选择课程</option>';
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('addGradeModal'));
        modal.show();
    }

    // 加载课程的学生列表
    function loadCourseStudents(courseId) {
        const studentSelect = document.getElementById('addStudentSelect');

        if (!courseId) {
            studentSelect.disabled = true;
            studentSelect.innerHTML = '<option value="">请先选择课程</option>';
            return;
        }

        // 显示加载状态
        studentSelect.disabled = true;
        studentSelect.innerHTML = '<option value="">正在加载学生列表...</option>';

        // 发送AJAX请求获取学生列表
        fetch('${pageContext.request.contextPath}/teacher/grades/courseStudents/' + courseId)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    studentSelect.innerHTML = '<option value="">请选择学生</option>';
                    if (data.students && data.students.length > 0) {
                        data.students.forEach(student => {
                            const option = document.createElement('option');
                            option.value = student.id;
                            option.textContent = student.user.realName + ' (' + student.studentNo + ')';
                            studentSelect.appendChild(option);
                        });
                        studentSelect.disabled = false;
                    } else {
                        studentSelect.innerHTML = '<option value="">该课程暂无学生</option>';
                    }
                } else {
                    console.error('获取学生列表失败:', data.message);
                    studentSelect.innerHTML = '<option value="">获取学生列表失败</option>';
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                studentSelect.innerHTML = '<option value="">网络错误，请重试</option>';
            });
    }

    // 提交添加成绩
    function submitAddGrade() {
        const form = document.getElementById('addGradeForm');
        const formData = new FormData(form);
        
        // 验证必填字段
        const courseId = formData.get('courseId');
        const studentId = formData.get('studentId');
        const regularScore = formData.get('regularScore');
        const examScore = formData.get('examScore');
        
        if (!courseId) {
            alert('请选择课程');
            return;
        }

        if (!studentId) {
            alert('请选择学生');
            return;
        }

        if (!regularScore && !examScore) {
            alert('请至少输入平时成绩或考试成绩');
            return;
        }

        // 显示加载状态
        const submitBtn = event.target;
        const originalText = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>提交中...';

        // 发送AJAX请求
        fetch('${pageContext.request.contextPath}/teacher/grades/add', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
                    if (data.success) {
                alert('成绩添加成功！');
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('addGradeModal'));
                modal.hide();
                // 刷新页面
                location.reload();
                    } else {
                alert('添加失败：' + data.message);
                }
            })
            .catch(error => {
            console.error('请求失败:', error);
            alert('网络错误，请重试');
        })
        .finally(() => {
            // 恢复按钮状态
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        });
    }

    // 编辑成绩
    function editGrade(gradeId) {
        // 显示加载状态
        document.getElementById('editGradeId').value = gradeId;
        document.getElementById('editStudentName').textContent = '加载中...';
        document.getElementById('editCourseName').textContent = '加载中...';
        document.getElementById('editRegularScore').value = '';
        document.getElementById('editExamScore').value = '';
        
        const editModal = new bootstrap.Modal(document.getElementById('editGradeModal'));
        editModal.show();
        
        // 发送AJAX请求获取成绩详情
        fetch('${pageContext.request.contextPath}/teacher/grades/view/' + gradeId)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.grade) {
                    const grade = data.grade;
                    // 填充学生和课程信息
                    document.getElementById('editStudentName').textContent = 
                        (grade.student && grade.student.user) ? grade.student.user.realName : '未知学生';
                    document.getElementById('editCourseName').textContent = 
                        grade.course ? grade.course.name : '未知课程';
                    
                    // 填充成绩信息
                    document.getElementById('editRegularScore').value = grade.regularScore || '';
                    document.getElementById('editExamScore').value = grade.examScore || '';
                } else {
                    console.error('获取成绩详情失败:', data.message);
                    document.getElementById('editStudentName').textContent = '获取信息失败';
                    document.getElementById('editCourseName').textContent = '获取信息失败';
                    alert('获取成绩详情失败：' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('请求失败:', error);
                document.getElementById('editStudentName').textContent = '网络错误';
                document.getElementById('editCourseName').textContent = '网络错误';
                alert('网络错误，请稍后再试');
            });
    }

    // 提交编辑成绩
    function submitEditGrade() {
        const gradeId = document.getElementById('editGradeId').value;
        const regularScore = document.getElementById('editRegularScore').value;
        const examScore = document.getElementById('editExamScore').value;
        
        if (!regularScore && !examScore) {
            alert('请至少输入平时成绩或考试成绩');
            return;
        }

        const formData = new FormData();
        formData.append('id', gradeId);
        if (regularScore) formData.append('regularScore', regularScore);
        if (examScore) formData.append('examScore', examScore);

        // 发送AJAX请求
        fetch('${pageContext.request.contextPath}/teacher/grades/update', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('成绩更新成功！');
                // 关闭模态框
                const modal = bootstrap.Modal.getInstance(document.getElementById('editGradeModal'));
                modal.hide();
                // 刷新页面
                location.reload();
            } else {
                alert('更新失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            alert('网络错误，请重试');
        });
    }

    // 删除成绩
    function deleteGrade(gradeId) {
        if (confirm('确定要删除这条成绩记录吗？')) {
        window.location.href = '${pageContext.request.contextPath}/teacher/grades/delete/' + gradeId;
        }
    }
</script>
</body>
</html>

